package com.sinaapp.zhangziyou.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sinaapp.zhangziyou.dao.MainDao;
import com.sinaapp.zhangziyou.dao.TagDao;
import com.sinaapp.zhangziyou.dao.TagMainDao;
import com.sinaapp.zhangziyou.pojo.MainEntity;
import com.sinaapp.zhangziyou.pojo.TagEntity;
import com.sinaapp.zhangziyou.pojo.TagMain;
import com.sinaapp.zhangziyou.security.WebUserDetails;
import com.sinaapp.zhangziyou.service.ACenterService;
import com.sinaapp.zhangziyou.utils.DateUtil;
import com.sinaapp.zhangziyou.utils.MD5;
import com.sinaapp.zhangziyou.utils.UUIDGenerator;

@Service("aCenterService")
public class ACenterServiceImpl implements ACenterService {
	@Autowired
	private MainDao mainDao;
	@Autowired
	private TagDao tagDao;
	@Autowired
	private TagMainDao tagMainDao;

	/* (non-Javadoc)
	 * @see com.sinaapp.zhangziyou.service.ACenterService#saveMainEntity(com.sinaapp.zhangziyou.pojo.MainEntity, com.sinaapp.zhangziyou.pojo.TagEntity)
	 */
	@Override
	@Transactional
	public void saveMainEntity(MainEntity mainEntity, TagEntity tagEntity) {
		WebUserDetails webUserDetails = (WebUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String userId = webUserDetails.getUserId();
		// TODO logo还没有呢
		String linkMd5 = MD5.getMD5Encoding(mainEntity.getLink());
		mainEntity.setLinkMd5(linkMd5);
		mainEntity.setStatus(1);
		mainEntity.setUpdateTime(DateUtil.getCurrentTime());
		mainEntity.setId(UUIDGenerator.getUUID());
		mainEntity.setVersion(1);
		mainDao.save(mainEntity);
		
		//TODO 标签 分割问题 和标签存在问题
		String[] tags = tagEntity.getName().split(",");
		for (String tag : tags) {
			if(tagDao.existTag(tag)<=0){
				TagEntity tagEnt = new TagEntity();
				tagEnt.setUserId(userId);
				tagEnt.setId(UUIDGenerator.getUUID());
				tagEnt.setStatus(1);
				tagEnt.setUpdateTime(DateUtil.getCurrentTime());
				tagEnt.setName(tag);
				
				TagMain tagMain = new TagMain();
				tagMain.setUserId(userId);
				tagMain.setId(UUIDGenerator.getUUID());
				tagMain.setVersion(1);
				tagMain.setCreateTime(DateUtil.getCurrentTime());
				tagMain.setTagId(tagEnt.getId());
				tagMain.setMainId(mainEntity.getId());
				
				tagDao.save(tagEnt);
				tagMainDao.saveKindMain(tagMain);
			}
		}
	}

}
